<template>
  <div class="seat-map-container">
    <!-- 图例区域 -->
    <div class="legend-container">
      <div class="legend-scroll">
        <!-- 已售座位图例 -->
        <div class="legend-item">
          <div>
            <img style="width:16px;height:16px" :src="$buildFullImageUrl + selectedImage" alt="已售">
          </div>
          <span class="legend-text">已售</span>
        </div>

        <!-- 价格区域图例 -->
        <div v-for="(area, index) in sortedAreaData" :key="index" class="legend-item">
          <div :class="['area-legend', `area-${index}`]" :style="{ borderColor: area.color }"></div>
          <span class="legend-text">¥{{ area.price }}</span>
        </div>

        <!-- 不可售图例 -->
        <!-- <div class="legend-item">
          <div class="sold-seat"></div>
          <span class="legend-text">不可售</span>
        </div> -->

        <!-- 新增情侣座位图例 -->
        <div class="legend-item">
          <div class="couple-seat-legend"></div>
          <span class="legend-text">情侣座</span>
        </div>
      </div>
    </div>

    <!-- 影厅名称 -->
    <div class="positions">
      <div><img src="../assets/index/films.png" alt="" class="file_position"></div>
      <div class="names">{{ showName }}</div>
    </div>

    <!-- 座位图主体 -->
    <div class="seat-map-scroll-container">
      <!-- 行号标签 - 固定在左侧 -->
      <div class="row-labels">
        <div v-for="row in uniqueRows" :key="row" class="row-label">{{ row }}</div>
      </div>

      <!-- 可滚动的座位图 -->
      <div class="seat-map-wrapper" ref="seatMapWrapper">
        <div class="seat-map" ref="seatMap">
          <!-- 中线 -->
          <!-- <div class="center-line" :style="centerLineStyle" v-if="seat_list.length"></div> -->

          <!-- 动态生成的行和列 -->
          <div v-for="row in uniqueRows" :key="row" class="seat-row">
            <!-- 根据column值精确放置每个座位 -->
            <template v-for="(col) in maxColumns">
              <div v-if="hasSeat(row, col)" class="seat-col" :style="getCoupleSeatStyle(row, col)">
                <van-button :class="getSeatClass(row, col)" :style="getSeatStyle(row, col)"
                  :disabled="!isSeatAvailable(row, col)" @click="handleSeatClick(row, col)" size="mini">
                  <img v-if="!isSeatAvailable(row, col)" class="sold-seat-img" style="width: 18px;height: 18px;"
                    :src="$buildFullImageUrl + selectedImage" alt="已售">
                </van-button>
              </div>
              <!-- 没有座位的空位 -->
              <div v-else class="empty-col"></div>
            </template>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    area_data: {
      type: String,
      default: ""
    },
    selectedSeats: {
      type: Array,
      default: () => []
    },
    showName: {
      type: String,
      default: "1号厅"
    },
    max_can_buy: {
      type: Number,
      default: 4
    },
    selectedImage: {
      type: String,
      default: ''
    },
    seat_list: {
      type: Array,
      default: () => []
    }
  },

  data() {
    return {
      localSelectedSeats: [],
      colors: ["#196EE2", "#ff976a", "#ee0a24", "#e485dc", "#81e67d", "#91d6f0", "#770c81", "#1c7a7a"],
      maxSeats: 5,
      selectedPerson: 0,
      autoSelectedSeats: [],
      seatStyles: {},
      sortedAreaData: [],
      seatMapHeight: 0
    };
  },

  computed: {
    uniqueRows() {
      const rows = new Set(this.seat_list.map(seat => seat.row));
      return Array.from(rows).sort((a, b) => a - b);
    },

    maxColumns() {
      return Math.max(...this.seat_list.map(seat => seat.column));
    },

    maxRows() {
      return Math.max(...this.seat_list.map(seat => seat.row));
    },

    centerLineStyle() {
      const seatWidth = 18;
      const gapWidth = 5;
      const isEvenColumns = this.maxColumns % 2 === 0;

      let centerPosition;
      if (isEvenColumns) {
        const middleRight = this.maxColumns / 2;
        centerPosition = (middleRight * seatWidth) + ((middleRight - 1) * gapWidth) + (gapWidth / 2);
      } else {
        const middle = Math.ceil(this.maxColumns / 2);
        centerPosition = (middle * seatWidth) + ((middle - 1) * gapWidth) + (gapWidth / 2);
      }

      return {
        left: `${centerPosition}px`,
        height: `${this.seatMapHeight}px`,
      };
    }
  },

  watch: {
    selectedSeats: {
      immediate: true,
      handler(newVal) {
        this.localSelectedSeats = [...newVal];
      }
    },
    area_data: {
      immediate: true,
      handler(newVal) {
        if (newVal) this.parseAndSortAreaData();
      }
    },
    uniqueRows: {
      immediate: true,
      handler() {
        this.$nextTick(() => {
          this.calculateSeatMapHeight();
        });
      }
    }
  },

  mounted() {
    this.parseAndSortAreaData();
    this.$nextTick(() => {
      this.calculateSeatMapHeight();
    });
  },

  methods: {
    calculateSeatMapHeight() {
      if (this.$refs.seatMap) {
        const rows = this.$refs.seatMap.querySelectorAll('.seat-row');
        if (rows.length > 0) {
          const rowHeight = rows[0].offsetHeight;
          const rowGap = 3;
          this.seatMapHeight = rows.length * (rowHeight + rowGap) - rowGap;
        }
      }
    },

    hasSeat(row, col) {
      const seat = this.seat_list.find(item => item.row === row && item.column === col);
      // 如果是情侣右座(2)，需要检查左座(1)是否存在
      if (seat && seat.flag === 2) {
        const leftSeat = this.seat_list.find(item =>
          item.row === row &&
          item.column === col - 1 &&
          item.flag === 1
        );
        return !!leftSeat;
      }
      return !!seat;
    },

    parseAndSortAreaData() {
      if (!this.area_data) return;

      const areas = this.area_data.split(';').map(item => {
        const parts = item.trim().split(',');
        const areaPart = parts[0].split(':');
        const pricePart = parts[1].split(':');
        return {
          area_id: areaPart[1],
          price: parseFloat(pricePart[1]),
          settle_price: parts[2] ? parseFloat(parts[2].split(':')[1]) : 0
        };
      });

      areas.sort((a, b) => a.price - b.price);
      this.sortedAreaData = areas.map((area, index) => ({
        ...area,
        color: this.colors[index % this.colors.length]
      }));
    },

    getSeatStyle(row, col) {
      const seat = this.seat_list.find(item => item.row === row && item.column === col);

      // 情侣座位特殊样式
      if (seat && (seat.flag === 1 || seat.flag === 2)) {
        return {
          borderColor: '#ff69b4',
          borderWidth: '1px',
          borderStyle: 'solid',
          borderRadius: seat.flag === 1 ? '4px 0 0 4px' : '0 4px 4px 0',
          backgroundColor: '#ffebf2'
        };
      }

      // 不可售座位
      if (seat && seat.status === 0) {
        return {
          borderColor: '#c8c9cc',
          borderWidth: '1px',
          borderStyle: 'solid'
        };
      }

      if (!this.area_data) {
        return {
          borderColor: this.colors[0],
          borderWidth: '1px',
          borderStyle: 'solid'
        };
      }

      if (seat && seat.area_id) {
        const area = this.sortedAreaData.find(a => a.area_id === seat.area_id);
        if (area) {
          return {
            borderColor: area.color,
            borderWidth: '1px',
            borderStyle: 'solid'
          };
        }
      }
      return {};
    },

    getCoupleSeatStyle(row, col) {
      const seat = this.seat_list.find(item => item.row === row && item.column === col);
      if (seat && (seat.flag === 1 || seat.flag === 2)) {
        return {
          position: 'relative',
          zIndex: seat.flag === 1 ? 2 : 1,
          marginRight: seat.flag === 1 ? '-1px' : '0',
          marginLeft: seat.flag === 2 ? '-1px' : '0'
        };
      }
      return {};
    },

    getSeatClass(row, col) {
      const seat = this.seat_list.find(item => item.row === row && item.column === col);
      if (!seat) return 'seat-button';

      let className = 'seat-button';
      const seatName = seat.seat_name;
      const isSelected = this.localSelectedSeats.includes(seatName);
      const isAutoSelected = this.autoSelectedSeats.includes(seatName);

      // 添加情侣座位类
      if (seat.flag === 1) {
        className += ' couple-seat-left';
      } else if (seat.flag === 2) {
        className += ' couple-seat-right';
      }

      if (isSelected) {
        className += ' seat-selected';
      } else if (isAutoSelected) {
        className += ' seat-auto-selected';
      } else if (seat.status !== 1) {
        className += ' seat-unavailable';
      } else if (seat.area_id) {
        className += ' seat-area';
        if (!this.seatStyles[seatName]) {
          this.$set(this.seatStyles, seatName, {
            borderColor: this.area_data
              ? (this.sortedAreaData.find(a => a.area_id === seat.area_id)?.color || this.colors[0])
              : this.colors[0]
          });
        }
      }

      return className;
    },

    handleSeatClick(row, col) {
      const seat = this.seat_list.find(item => item.row === row && item.column === col);
      if (!seat || seat.status !== 1) return;

      const seatName = seat.seat_name;
      let newSelectedSeats = [...this.localSelectedSeats];
      const seatIndex = newSelectedSeats.indexOf(seatName);
      // 处理情侣座位联动
      if (seat.flag === 1 || seat.flag === 2) {
        // 查找配对座位（左座找右座，右座找左座）
        const partnerCol = seat.flag === 1 ? col + 1 : col - 1;
        const partnerSeat = this.seat_list.find(item =>
          item.row === row &&
          item.column === partnerCol &&
          (item.flag === (seat.flag === 1 ? 2 : 1))
        );

        const partnerSeatName = partnerSeat?.seat_name;

        if (seatIndex >= 0) {
          // 取消选择当前座位
          newSelectedSeats.splice(seatIndex, 1);
          // 如果存在配对座位也取消选择
          if (partnerSeatName) {
            const partnerIndex = newSelectedSeats.indexOf(partnerSeatName);
            if (partnerIndex >= 0) {
              newSelectedSeats.splice(partnerIndex, 1);
            }
          }
        } else {
          // 检查是否超过最大可选数量
          const seatsToAdd = partnerSeatName ? [seatName, partnerSeatName] : [seatName];
          if (newSelectedSeats.length + seatsToAdd.length > this.max_can_buy) {
            this.$toast(`最多选择${this.max_can_buy}个座位`);
            return;
          }
          // 添加当前座位和配对座位
          newSelectedSeats.push(...seatsToAdd);
        }
      } else {
        // 普通座位处理逻辑
        if (seatIndex >= 0) {
          newSelectedSeats.splice(seatIndex, 1);
        } else {
          if (newSelectedSeats.length >= this.max_can_buy) {
            this.$toast(`最多选择${this.max_can_buy}个座位`);
            return;
          }
          newSelectedSeats.push(seatName);
        }
      }

      this.localSelectedSeats = newSelectedSeats;
      this.$emit('update-selected', newSelectedSeats);
    },

    isSeatAvailable(row, col) {
      const seat = this.seat_list.find(item => item.row === row && item.column === col);
      return seat && seat.status === 1;
    },

    getSeatName(row, col) {
      const seat = this.seat_list.find(item => item.row === row && item.column === col);
      return seat ? seat.seat_name.split('排')[1] : '';
    },

    autoSelectBestSeats(num) {
      this.autoSelectedSeats = [];
      const centerRow = Math.ceil(this.maxRows / 2);
      const centerCol = Math.ceil(this.maxColumns / 2);

      for (let i = 0; i < num; i++) {
        const seat = `${centerRow}排${centerCol + i}`;
        if (this.isSeatAvailable(centerRow, centerCol + i)) {
          this.autoSelectedSeats.push(seat);
        }
      }
    }
  }
};
</script>

<style scoped>
.seat-map-container {
  padding: 0 15px;
  text-align: center;
  border: none;
}

.legend-container {
  width: 100%;
  padding: 8px 0;
  overflow-x: auto;
  scrollbar-width: none;
}

.legend-container::-webkit-scrollbar {
  display: none;
}

.legend-scroll {
  display: inline-flex;
  align-items: center;
  gap: 16px;
  white-space: nowrap;
  padding-bottom: 6px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 6px;
  >div:nth-child(1){
    display: flex;
    align-items: center;
  }
}

.legend-text {
  font-size: 12px;
  color: #333;
  line-height: 1;
}

.area-legend,
.sold-seat,
.couple-seat-legend {
  width: 14px;
  height: 14px;
  border-radius: 4px;
  flex-shrink: 0;
  background: #FFFFFF;
  border: 1px solid;
}

.sold-seat {
  border-color: #c8c9cc;
}

.couple-seat-legend {
  border-color: #ff69b4;
  background-color: #ffebf2;
}

.positions {
  position: relative;
  margin-bottom: 65px;
  width: 100%;
  margin-top: 15px;
  text-align: center;
}

.file_position {
  width: 200px;
  height: 28px;
  position: absolute;
  left: 50%;
  top: 0;
  transform: translateX(-50%);
}

.names {
  padding: 0;
  margin: 0;
  font-family: PingFang SC;
  font-size: 12px;
  color: #797979;
  position: absolute;
  left: 50%;
  top: 18px;
  transform: translateX(-50%);
  white-space: nowrap;
}

.seat-map-scroll-container {
  position: relative;
  display: flex;
  width: 100%;
  overflow: hidden;
}

.row-labels {
  position: sticky;
  left: 0;
  top: 0;
  z-index: 2;
  width: 20px;
  background: rgba(0, 0, 0, 0.2);
  border-radius: 20px;
  flex-shrink: 0;
}

.row-label {
  height: 24px;
  line-height: 24px;
  text-align: center;
  margin-bottom: 3px;
  font-family: PingFang SC;
  font-weight: 400;
  font-size: 10px;
  color: #FFFFFF;
}

.seat-map-wrapper {
  flex-grow: 1;
  overflow-x: auto;
  scrollbar-width: none;
  position: relative;
  margin-left: 15px;
}

.seat-map {
  position: relative;
  display: flex;
  flex-direction: column;
  gap: 3px;
  width: fit-content;
  padding-left: 0;
}

.center-line {
  position: absolute;
  top: 0;
  left: 0;
  border-left: 1px dashed #ccc;
  z-index: 1;
  pointer-events: none;
  background-color: transparent;
}

.seat-row {
  display: flex;
  align-items: center;
  gap: 5px;
  position: relative;
  height: 24px;
}

.seat-col,
.empty-col {
  width: 18px;
  height: 18px;
}

.empty-col {
  visibility: hidden;
}

.seat-button {
  width: 100%;
  height: 100%;
  padding: 0;
  min-height: auto;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #FFFFFF !important;
  border: 1px solid transparent;
  font-size: 10px;
}

/* 情侣座位样式 */
.couple-seat-left {
  border-radius: 4px 0 0 4px !important;
}

.couple-seat-right {
  border-radius: 0 4px 4px 0 !important;
}

/* 选中状态下的情侣座位 */
.couple-seat-left.seat-selected,
.couple-seat-right.seat-selected {
  background-color: #ff69b4 !important;
  color: white !important;
}

/* 不可用状态下的情侣座位 */
.couple-seat-left.seat-unavailable,
.couple-seat-right.seat-unavailable {
  background-color: #f5f5f5 !important;
  opacity: 0.6;
}

.seat-selected {
  background-color: #ff4444 !important;
  color: white !important;
}

.seat-auto-selected {
  background-color: #42a5f5 !important;
  color: white !important;
}

.seat-unavailable {
  background-color: #f5f5f5;
  color: #c62828;
  opacity: 0.6;
}

.sold-seat-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 2px;
}

.seat-area {
  background: #FFFFFF;
  border: 1px solid;
}
</style>
